import React, { Component } from 'react';
import { Modal, Input, message } from 'antd';
import PropTypes from 'prop-types';
import cn from 'classnames';
import CheckboxSelect from '@components/checkbox-select';
import { addOnedayStrategy, updateOnedayStrategy } from '@api/task';
import { NAME_RE } from '@util/constants';
import { get, pickBy } from 'lodash';
import './index.less';

class ConfigModal extends Component {
  static defaultState = {
    strategyName: '',
    strategyNameError: '',
    selectedOnedays: [],
    selectedOnedaysError: '',
    isConfigingTemplate: false,
    id: ''
  };

  constructor(props) {
    super(props);
    this.state = ConfigModal.defaultState;
    this.id = '';
  }

  // eslint-disable-next-line
  UNSAFE_componentWillReceiveProps(props) {
    const { current } = props;
    if (current && typeof current === 'object') {
      // eslint-disable-next-line
      const { _id: id, name: strategyName, oneday_detail_oids: selectedOnedaysOrigin } = current;
      const selectedOnedays = selectedOnedaysOrigin
        .map(oneday => get(oneday, '_id'))
        .filter(i => i);

      this.setState({
        id,
        strategyName,
        selectedOnedays
      });
    }
  }

  resetState = () => {
    this.setState(ConfigModal.defaultState);
  };

  onOKTemplate = () => {
    const {
      strategyName,
      selectedOnedays,
      id,
      strategyNameError,
      selectedOnedaysError
    } = this.state;
    if (strategyNameError || selectedOnedaysError) {
      return;
    }
    let nameError = '',
      onedaysError = '';
    if (!strategyName) {
      nameError = '策略名称不能为空';
    }
    if (!selectedOnedays.length) {
      onedaysError = '插件选择不能为空';
    }
    if (nameError || onedaysError) {
      this.setState({
        strategyNameError: nameError,
        selectedOnedaysError: onedaysError
      });
      return;
    }
    this.setState({ isConfigingTemplate: true });
    let todo = id ? updateOnedayStrategy : addOnedayStrategy;
    const body = pickBy(
      {
        // eslint-disable-next-line
        strategy_id: id,
        name: strategyName,
        // eslint-disable-next-line
        oneday_detail_ids: selectedOnedays
      },
      Boolean
    );
    todo(body)
      .then(() => {
        message.success(id ? '编辑成功' : '添加成功');
        if (typeof this.props.onSuccess === 'function') {
          this.resetState();
          this.props.onSuccess();
        }
      })
      .catch(({ message: msg }) => {
        if (msg === 'strategy is exsit!') {
          message.error('漏洞策略模板名称已存在');
        } else {
          message.error(id ? '编辑失败' : '添加失败');
        }
      })
      .finally(() => {
        this.setState({ isConfigingTemplate: false });
      });
  };

  onModalCancel = () => {
    this.resetState();
    if (typeof this.props.onCancel === 'function') {
      this.props.onCancel();
    }
  };

  onChangeStrategyName = e => {
    const name = e.target.value;
    let error = '';
    if (!name) {
      error = '策略名称不能为空';
    }
    if (!NAME_RE.test(name)) {
      error = '策略名称格式不正确';
    }
    if (name.length > 32) {
      error = '策略名称不能超过32个字符';
    }
    this.setState({
      strategyName: name,
      strategyNameError: error
    });
  };

  onSelectOnedays = keys => {
    let error = '';
    if (!keys.length) {
      error = '插件选择不能为空';
    }
    this.setState({
      selectedOnedays: keys,
      selectedOnedaysError: error
    });
  };

  render() {
    const { visible, data } = this.props;
    const {
      isConfigingTemplate,
      strategyName,
      strategyNameError,
      selectedOnedays,
      selectedOnedaysError
    } = this.state;
    return (
      <Modal
        maskClosable={false}
        title="添加漏洞策略模板"
        className={cn('st-c-config-modal', 'no-header-bottom-lines', 'bottom-center', 'padding-24')}
        visible={visible}
        onCancel={this.onModalCancel}
        onOk={this.onOKTemplate}
        confirmLoading={isConfigingTemplate}
        destroyOnClose
      >
        <div className="config-modal__name">
          <span className="label">名称</span>
          <Input
            className="name"
            value={strategyName}
            onChange={this.onChangeStrategyName}
            placeholder="请输入数字、中文或英文，不超过32个字符"
          />
        </div>
        {strategyNameError && <p className="validate-error">{strategyNameError}</p>}
        <div className="config-modal__plugins">
          <span className="label">插件选择</span>
          <CheckboxSelect
            className="plugins"
            placeholder="请输入插件名称进行搜索"
            options={data}
            selected={selectedOnedays}
            onChange={this.onSelectOnedays}
          />
        </div>
        {selectedOnedaysError && <p className="validate-error">{selectedOnedaysError}</p>}
      </Modal>
    );
  }
}

ConfigModal.propTypes = {
  visible: PropTypes.bool,
  data: PropTypes.array,
  onCancel: PropTypes.func,
  onSuccess: PropTypes.func,
  current: PropTypes.object
};

export default ConfigModal;
